<template>
  <div class="charging-pile-category">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2>充电桩分类管理</h2>
      <el-button type="primary" @click="handleAdd">
        <el-icon><Plus /></el-icon>
        新增分类
      </el-button>
    </div>

    <!-- 搜索区域 -->
    <div class="search-area">
      <el-form :model="searchForm" inline>
        <el-form-item label="分类名称">
          <el-input
            v-model="searchForm.categoryName"
            placeholder="请输入分类名称"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="分类类型">
          <el-select
            v-model="searchForm.categoryType"
            placeholder="请选择分类类型"
            clearable
            style="width: 200px"
          >
            <el-option label="机动车直流快充" :value="1" />
            <el-option label="机动车交流慢充" :value="2" />
            <el-option label="非机动车充电桩" :value="3" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select
            v-model="searchForm.status"
            placeholder="请选择状态"
            clearable
            style="width: 150px"
          >
            <el-option label="启用" :value="1" />
            <el-option label="禁用" :value="0" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="handleReset">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 数据表格 -->
    <div class="table-area">
      <el-table
        v-loading="loading"
        :data="filteredTableData"
        border
        stripe
        style="width: 100%"
      >
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="categoryName" label="分类名称" min-width="150" />
        <el-table-column prop="categoryCode" label="分类编码" min-width="150" />
        <el-table-column prop="categoryTypeName" label="分类类型" min-width="150" />
        <el-table-column prop="powerRangeDesc" label="功率范围" min-width="120" />
        <el-table-column prop="voltageRange" label="电压范围" min-width="120" />
        <el-table-column prop="currentRange" label="电流范围" min-width="120" />
        <el-table-column prop="connectorTypes" label="接口类型" min-width="150" show-overflow-tooltip />
        <el-table-column prop="applicableVehicle" label="适用车辆" min-width="150" show-overflow-tooltip />
        <el-table-column prop="statusName" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.status === 1 ? 'success' : 'danger'">
              {{ row.statusName }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="sortOrder" label="排序" width="80" />
        <el-table-column prop="createTime" label="创建时间" width="180" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="handleEdit(row)">
              编辑
            </el-button>
            <el-button
              :type="row.status === 1 ? 'warning' : 'success'"
              size="small"
              @click="handleToggleStatus(row)"
            >
              {{ row.status === 1 ? '禁用' : '启用' }}
            </el-button>
            <el-button type="danger" size="small" @click="handleDelete(row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-area">
        <el-pagination
          v-model:current-page="pagination.current"
          v-model:page-size="pagination.size"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="800px"
      @close="handleDialogClose"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="120px"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="分类名称" prop="categoryName">
              <el-input v-model="formData.categoryName" placeholder="请输入分类名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="分类编码" prop="categoryCode">
              <el-input v-model="formData.categoryCode" placeholder="请输入分类编码" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="分类类型" prop="categoryType">
              <el-select v-model="formData.categoryType" placeholder="请选择分类类型" style="width: 100%">
                <el-option label="机动车直流快充" :value="1" />
                <el-option label="机动车交流慢充" :value="2" />
                <el-option label="非机动车充电桩" :value="3" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="排序" prop="sortOrder">
              <el-input-number v-model="formData.sortOrder" :min="0" style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="最小功率(kW)" prop="minPower">
              <el-input-number
                v-model="formData.minPower"
                :min="0"
                :precision="2"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="最大功率(kW)" prop="maxPower">
              <el-input-number
                v-model="formData.maxPower"
                :min="0"
                :precision="2"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="电压范围" prop="voltageRange">
              <el-input v-model="formData.voltageRange" placeholder="如：220V-380V" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="电流范围" prop="currentRange">
              <el-input v-model="formData.currentRange" placeholder="如：16A-63A" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="接口类型" prop="connectorTypes">
          <el-input
            v-model="formData.connectorTypes"
            placeholder="如：CCS,CHAdeMO,GB/T"
            show-word-limit
            maxlength="200"
          />
        </el-form-item>

        <el-form-item label="充电模式" prop="chargingMode">
          <el-input v-model="formData.chargingMode" placeholder="如：直流快充" />
        </el-form-item>

        <el-form-item label="适用车辆类型" prop="applicableVehicle">
          <el-input
            v-model="formData.applicableVehicle"
            placeholder="如：电动汽车,插电混动"
            show-word-limit
            maxlength="100"
          />
        </el-form-item>

        <el-form-item label="安装要求" prop="installationRequirements">
          <el-input
            v-model="formData.installationRequirements"
            type="textarea"
            :rows="3"
            placeholder="请输入安装要求"
            show-word-limit
            maxlength="500"
          />
        </el-form-item>

        <el-form-item label="安全标准" prop="safetyStandards">
          <el-input
            v-model="formData.safetyStandards"
            placeholder="如：GB/T 20234,IEC 62196"
            show-word-limit
            maxlength="200"
          />
        </el-form-item>

        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="formData.status">
                          <el-radio :value="1">启用</el-radio>
              <el-radio :value="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitLoading">
          确定
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessageBox } from 'element-plus'
import { Plus, Search, Refresh } from '@element-plus/icons-vue'
import { showMessage } from '@/utils/message'

// 类型定义
interface ChargingPileCategory {
  id: number
  categoryName: string
  categoryCode: string
  categoryType: number
  categoryTypeName: string
  minPower: number
  maxPower: number
  powerRangeDesc: string
  voltageRange: string
  currentRange: string
  connectorTypes: string
  chargingMode: string
  applicableVehicle: string
  installationRequirements: string
  safetyStandards: string
  status: number
  statusName: string
  sortOrder: number
  createTime: string
}

// 响应式数据
const loading = ref(false)
const submitLoading = ref(false)
const dialogVisible = ref(false)
const dialogTitle = ref('')
const isEdit = ref(false)
const currentId = ref<number | null>(null)

// 静态数据
const allTableData = ref<ChargingPileCategory[]>([
  {
    id: 1,
    categoryName: '直流快充桩',
    categoryCode: 'DC_FAST',
    categoryType: 1,
    categoryTypeName: '机动车直流快充',
    minPower: 30,
    maxPower: 350,
    powerRangeDesc: '30-350kW',
    voltageRange: '400V-750V',
    currentRange: '125A-500A',
    connectorTypes: 'CCS,CHAdeMO,GB/T',
    chargingMode: '直流快充',
    applicableVehicle: '电动汽车,插电混动',
    installationRequirements: '需要专用变压器和配电设备',
    safetyStandards: 'GB/T 20234.1-2015',
    status: 1,
    statusName: '启用',
    sortOrder: 1,
    createTime: '2024-01-01 10:00:00'
  },
  {
    id: 2,
    categoryName: '交流慢充桩',
    categoryCode: 'AC_SLOW',
    categoryType: 2,
    categoryTypeName: '机动车交流慢充',
    minPower: 3.5,
    maxPower: 22,
    powerRangeDesc: '3.5-22kW',
    voltageRange: '220V-380V',
    currentRange: '16A-32A',
    connectorTypes: 'Type2,GB/T',
    chargingMode: '交流慢充',
    applicableVehicle: '电动汽车,插电混动',
    installationRequirements: '标准家用或商用电源即可',
    safetyStandards: 'GB/T 20234.2-2015',
    status: 1,
    statusName: '启用',
    sortOrder: 2,
    createTime: '2024-01-02 11:00:00'
  },
  {
    id: 3,
    categoryName: '电动自行车充电桩',
    categoryCode: 'EBIKE_CHARGER',
    categoryType: 3,
    categoryTypeName: '非机动车充电桩',
    minPower: 0.5,
    maxPower: 2,
    powerRangeDesc: '0.5-2kW',
    voltageRange: '220V',
    currentRange: '2A-10A',
    connectorTypes: 'USB-C,Type-C',
    chargingMode: '交流充电',
    applicableVehicle: '电动自行车,电动摩托车',
    installationRequirements: '普通家用电源即可',
    safetyStandards: 'GB 17761-2018',
    status: 1,
    statusName: '启用',
    sortOrder: 3,
    createTime: '2024-01-03 12:00:00'
  }
])

const formRef = ref()

// 搜索表单
const searchForm = reactive({
  categoryName: '',
  categoryType: null as number | null,
  status: null as number | null
})

// 分页
const pagination = reactive({
  current: 1,
  size: 10,
  total: 0
})

// 表单数据
const formData = reactive({
  categoryName: '',
  categoryCode: '',
  categoryType: 1,
  minPower: null as number | null,
  maxPower: null as number | null,
  voltageRange: '',
  currentRange: '',
  connectorTypes: '',
  chargingMode: '',
  applicableVehicle: '',
  installationRequirements: '',
  safetyStandards: '',
  status: 1,
  sortOrder: 0
})

// 表单验证规则
const formRules = {
  categoryName: [
    { required: true, message: '请输入分类名称', trigger: 'blur' }
  ],
  categoryCode: [
    { required: true, message: '请输入分类编码', trigger: 'blur' }
  ],
  categoryType: [
    { required: true, message: '请选择分类类型', trigger: 'change' }
  ]
}

// 过滤后的表格数据
const filteredTableData = computed(() => {
  let filtered = [...allTableData.value]
  
  // 分类名称过滤
  if (searchForm.categoryName) {
    filtered = filtered.filter(item => 
      item.categoryName.toLowerCase().includes(searchForm.categoryName.toLowerCase())
    )
  }
  
  // 分类类型过滤
  if (searchForm.categoryType !== null) {
    filtered = filtered.filter(item => item.categoryType === searchForm.categoryType)
  }
  
  // 状态过滤
  if (searchForm.status !== null) {
    filtered = filtered.filter(item => item.status === searchForm.status)
  }
  
  // 更新分页总数
  pagination.total = filtered.length
  
  // 分页
  const start = (pagination.current - 1) * pagination.size
  const end = start + pagination.size
  return filtered.slice(start, end)
})

// 搜索
const handleSearch = () => {
  pagination.current = 1
  showMessage({ type: 'success', message: '搜索完成' })
}

// 重置搜索
const handleReset = () => {
  Object.assign(searchForm, {
    categoryName: '',
    categoryType: null,
    status: null
  })
  pagination.current = 1
  showMessage({ type: 'success', message: '重置完成' })
}

// 新增
const handleAdd = () => {
  isEdit.value = false
  dialogTitle.value = '新增充电桩分类'
  resetForm()
  dialogVisible.value = true
}

// 编辑
const handleEdit = (row: ChargingPileCategory) => {
  isEdit.value = true
  currentId.value = row.id
  dialogTitle.value = '编辑充电桩分类'
  Object.assign(formData, row)
  dialogVisible.value = true
}

// 删除
const handleDelete = async (row: ChargingPileCategory) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除分类"${row.categoryName}"吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    // 从静态数据中删除
    const index = allTableData.value.findIndex(item => item.id === row.id)
    if (index !== -1) {
      allTableData.value.splice(index, 1)
    }
    
    showMessage({ type: 'success', message: '删除成功' })
  } catch (error) {
    if (error !== 'cancel') {
      showMessage({ type: 'error', message: '删除失败' })
    }
  }
}

// 切换状态
const handleToggleStatus = async (row: ChargingPileCategory) => {
  try {
    const newStatus = row.status === 1 ? 0 : 1
    const statusNames = ['禁用', '启用']
    
    // 更新静态数据
    const index = allTableData.value.findIndex(item => item.id === row.id)
    if (index !== -1) {
      allTableData.value[index].status = newStatus
      allTableData.value[index].statusName = statusNames[newStatus]
    }
    
    showMessage({ type: 'success', message: '状态更新成功' })
  } catch (error) {
    showMessage({ type: 'error', message: '状态更新失败' })
  }
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    submitLoading.value = true
    
    // 模拟API调用延迟
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    if (isEdit.value && currentId.value) {
      // 更新现有分类
      const index = allTableData.value.findIndex(item => item.id === currentId.value)
      if (index !== -1) {
        const categoryTypeNames = ['', '机动车直流快充', '机动车交流慢充', '非机动车充电桩']
        const powerRangeDesc = `${formData.minPower}-${formData.maxPower}kW`
        
        Object.assign(allTableData.value[index], {
          ...formData,
          categoryTypeName: categoryTypeNames[formData.categoryType],
          powerRangeDesc,
          statusName: formData.status === 1 ? '启用' : '禁用'
        })
      }
      showMessage({ type: 'success', message: '更新成功' })
    } else {
      // 添加新分类
      const categoryTypeNames = ['', '机动车直流快充', '机动车交流慢充', '非机动车充电桩']
      const newCategory: ChargingPileCategory = {
        id: allTableData.value.length + 1,
        ...formData,
        categoryTypeName: categoryTypeNames[formData.categoryType],
        powerRangeDesc: `${formData.minPower}-${formData.maxPower}kW`,
        statusName: formData.status === 1 ? '启用' : '禁用',
        createTime: new Date().toLocaleString('zh-CN', {
          year: 'numeric',
          month: '2-digit',
          day: '2-digit',
          hour: '2-digit',
          minute: '2-digit',
          second: '2-digit'
        }).replace(/\//g, '-')
      }
      allTableData.value.unshift(newCategory)
      showMessage({ type: 'success', message: '创建成功' })
    }
    
    dialogVisible.value = false
  } catch (error) {
    showMessage({ type: 'error', message: '提交失败' })
  } finally {
    submitLoading.value = false
  }
}

// 重置表单
const resetForm = () => {
  Object.assign(formData, {
    categoryName: '',
    categoryCode: '',
    categoryType: 1,
    minPower: null,
    maxPower: null,
    voltageRange: '',
    currentRange: '',
    connectorTypes: '',
    chargingMode: '',
    applicableVehicle: '',
    installationRequirements: '',
    safetyStandards: '',
    status: 1,
    sortOrder: 0
  })
  formRef.value?.clearValidate()
}

// 关闭对话框
const handleDialogClose = () => {
  resetForm()
}

// 分页大小改变
const handleSizeChange = (size: number) => {
  pagination.size = size
  pagination.current = 1
}

// 当前页改变
const handleCurrentChange = (current: number) => {
  pagination.current = current
}

// 初始化
onMounted(() => {
  pagination.total = allTableData.value.length
})
</script>

<style scoped>
.charging-pile-category {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  color: #303133;
}

.search-area {
  background: #fff;
  padding: 20px;
  border-radius: 4px;
  margin-bottom: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.table-area {
  background: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.pagination-area {
  padding: 20px;
  text-align: right;
}
</style> 